﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using TjZheng.Framework;

namespace TjZheng.Example.MVC.Filter
{
    public class DecryptionFilter : FilterAttribute, IActionFilter
    {
        /// <summary>
        /// 是否加密
        /// </summary>
        protected bool IsDecrypt { get; set; }

        /// <summary>
        /// 请求接口的地址
        /// </summary>
        protected string RequestUrl { get; set; }

        /// <summary>
        /// 约定密钥
        /// </summary>
        protected string DecryptKey { get; set; }

        protected HttpMethod HttpMethod { get; set; }

        public DecryptionFilter(bool IsDecrypt, HttpMethod HttpMethod)
        {
            this.IsDecrypt = IsDecrypt;
            this.DecryptKey = GetDecryptKey();
            this.HttpMethod = HttpMethod;
        }

        public virtual void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (RequestUrl.IsNull())
            {
                filterContext.Result = new JsonResult
                {
                    Data = new InvokeResult
                    {
                        ResultCode = "RequestUrlNull",
                        ResultMessage = "返回结果格式错误"
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
            HttpHelper.CreateHttpGet("");
        }

        /// <summary>
        /// 自定义获取密钥方法，设置this.DecryptKey值
        /// </summary>
        protected virtual string GetDecryptKey()
        {
            return "";
        }

        /// <summary>
        /// 自定义加密算法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual string DecryptHandle(string data)
        {
            return data.DecodeBase64().Replace(this.DecryptKey, "");//
        }
    }
}